package org.example.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.example.domain.dto.SysUserDto;
import org.example.service.domain.SysUserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Resource
    private SysUserService sysUserService;

    @Override
    public void insertFill(MetaObject metaObject) {
        SysUserDto sysUser =  sysUserService.getLoginUserInfo();
        for (String name : metaObject.getGetterNames()) {
            if ("createUser".equals(name)&& Objects.nonNull(metaObject.getValue("createUser")) ) {
                this.strictInsertFill(metaObject, "createUser", String.class, sysUser.getUsername());
            }
            if ("updateUser".equals(name)&& Objects.nonNull(metaObject.getValue("updateUser")) ) {
                this.strictInsertFill(metaObject, "updateUser", String.class, sysUser.getUsername());
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        SysUserDto sysUser =  sysUserService.getLoginUserInfo();
        for (String name : metaObject.getGetterNames()) {
            if ("updateUser".equals(name)&& Objects.nonNull(metaObject.getValue("updateUser")) ) {
                this.strictInsertFill(metaObject, "updateUser", String.class, sysUser.getUsername());
            }
        }
    }
}
